package br.com.uniban.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import br.com.uniban.dao.base.DAOGeneric;
import br.com.uniban.entity.Disciplina;

public class  DAOGenericImpl<T, PK extends Serializable> implements DAOGeneric<T, PK> {

	@PersistenceContext(unitName = "EjbServicesUnit")
	private EntityManager em;

	private Class<T> entityClass;
	
	public DAOGenericImpl(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
	
	@Override
	public T create(T entity) {
		 em.persist(entity);
		return entity;
	}
	
	@Override
	public T getReference(PK pk) throws Exception {	 
		return (T) em.getReference(entityClass, pk);
	}

	@Override
	public T merge(T entity) {
		return this.em.merge(entity);
	}
	
	@Override
	public T find(PK pk) {
		return (T) em.find(entityClass, pk);

	}

	@Override
	public void delete(T entity) {
		entity = this.em.merge(entity);
		this.em.remove(entity);

	}
	@Override
	public List<Disciplina> listAllDisciplina() {
	
		return this.getEntityManager().createNamedQuery("Disciplina.findAll").getResultList();
		
	}
	
	@Override
	public Disciplina findDisciplina(Short pk) {
		return this.getEntityManager().getReference(Disciplina.class, pk);
	}

	protected String getMax(String queryName) {
		return this.em.createNamedQuery(queryName).getResultList().get(0).toString();
	}
	protected EntityManager getEntityManager() {
		return this.em;
	}

}
